require 'rubygame'
require 'data'

module OF7
	module Graphics
		
		class Sprite < Rubygame::Sprites::Sprite
			
			attr_reader   :sheet
			attr_accessor :x, :y, :a
			alias :z, :depth
			
			def initialize(img_path, x, y, d, a=255)
				super()
				
				@sheet = Util::load_image(img_path)
				@x, @y = x, y
				@depth = d
				@a = a
				@angle = 0
				@last_angle = @angle
			end
			
			def update(*args)
				cx, cy = @x + (@rect.width / 2), @y + (@rect.height / 2)
				@image = @image.rotozoom(@angle - @last_angle, [1.0, 1.0])
				@rect = @image.make_rect
				@rect.cx, @rect.cy = cx, cy
				@image.set_alpha(@a)
				@last_angle = @angle
			end
			
			def width
				truimg = image.rotozoom(-@last_angle, [1.0, 1.0])
				return truimg.width
			end
			
			def height
				truimg = image.rotozoom(-@last_angle, [1.0, 1.0])
				return truimg.height
			end
			
		end
		
		class Image < Sprite
			def initialize(img_path, x, y, d, a=255)
				super(img_path, x, y, d, a)
				
				@image = self.sheet
				@rect = @image.make_rect
			end
		end
		
		class Animation < Sprite
			attr_reader   :framerate
			attr_accessor :looping
			
			def initialize(img_path, x, y, d, w, h, a=255, fps=30)
				super(img_path, x, y, d, a)
				
				@width, @height = w, h
				@framerate = fps
				@frames = []
				
				self.width.times do |i|
					srf = Rubygame::Surface.new([@width, @height])
					src = Rubygame::Rect.new(@width * i, 0, @width, @height)
					@sheet.blit(srf, [0, 0], src)
					@frames << srf
				end
				
				@image = @frames[0]
				@rect = @image.make_rect
				@current_frame = 0
				@looping = true
			end
			
			def update(*args)
				dt = args[0]
				next_frame = @current_frame + (@framerate * dt / 1000).to_i
				
				if not @looping and next_frame >= frames.size - 1 then
					@current_frame = frames.size - 1
					@image = @frames[@current_frame]
					return
				end
				
				@current_frame = next_frame % frames.size
				@image = @frames[@current_frame]
				
				super.update
			end
			
			def width
				return @width
			end
			
			def height
				return @height
			end
		end
		
	end
end